﻿using DotnetSpider.Core;
using DotnetSpider.Core.Processor;
using System;
using System.Collections.Generic;

using AngleSharp.Html.Parser;
using SpiderPlatform.Entity;

namespace SpiderPlatform.Processor
{
    public class OscartProcessor : BasePageProcessor
    {
        private static HtmlParser htmlParser = new HtmlParser();
        protected override void Handle(Page page)
        {
            List<string> list = new List<string>();
            var modelHtml = page.Content;
            var dom = htmlParser.ParseDocument(page.Content);
            var HtmlList = dom.QuerySelectorAll("div.ui.card");
            foreach (var item in HtmlList)
            {
                var link = item.QuerySelector("a.image.item-img").GetAttribute("href");
                if (!string.IsNullOrEmpty(link))
                {
                    list.Add("https://www.oscart.com/"+link);
                }               
            }
            page.AddResultItem("ItemList", list);
        }
    }

    public class OscartDetailProcessor : BasePageProcessor
    {
        private static HtmlParser htmlParser = new HtmlParser();
        protected override void Handle(Page page)
        {
            var dom = htmlParser.ParseDocument(page.Content);
            OscartEntity entity = new OscartEntity();
            entity.link = page.Url;
            entity.id = entity.link.Substring(entity.link.LastIndexOf("/")+1);
            entity.name = dom.QuerySelector("div.item-title").InnerHtml;
            entity.images = dom.QuerySelector("div.campaign-img img").GetAttribute("data-src");
            entity.reviews = dom.QuerySelector("div.item-price .total-reviews").InnerHtml;
            entity.price = dom.QuerySelector("div.item-price .item-price-now").InnerHtml; 
            entity.old_price = dom.QuerySelector("div.item-price .item-price-was")?.InnerHtml;
            var buy = dom.QuerySelector("div.msg-title");
            if(buy!=null && buy.InnerHtml.Trim()== "售罄")
            {
                entity.is_instock = 0;
            }
            else
            {
                entity.is_instock = 1;
            }
            var breadcrumb = dom.QuerySelectorAll("div.ui.breadcrumb .section");
            entity.c1 = breadcrumb[1].InnerHtml;
            entity.c2 = breadcrumb[2].InnerHtml;
            page.AddResultItem("Item", entity);
        }
    }
}
